package com.spzx.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.RemoteOrderInfoService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.mapper.PaymentInfoMapper;
import com.spzx.payment.service.IPaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * 付款信息Service业务层处理
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements IPaymentInfoService {
    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private RemoteOrderInfoService remoteOrderInfoService;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 保存支付信息
     * <p>
     * 根据订单号查询支付信息，如果不存在则从订单服务获取订单信息并创建新的支付信息记录
     *
     * @param orderNo 订单号
     * @return 支付信息对象
     */
    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        // 根据订单号查询支付信息
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));

        // 如果支付信息不存在，则创建新的支付信息
        if (paymentInfo == null) {
            // 调用远程订单服务获取订单信息
            R<OrderInfo> orderInfoResult = remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
            if(R.FAIL==orderInfoResult.getCode()){
                throw new ServiceException(orderInfoResult.getMsg());
            }
            OrderInfo orderInfo = orderInfoResult.getData();

            // 构造支付信息对象
            paymentInfo = new PaymentInfo();
            paymentInfo.setUserId(orderInfo.getUserId());
            String content = "";
            for (OrderItem orderItem : orderInfo.getOrderItemList()) {
                content += orderItem.getSkuName() + "，";
            }
            paymentInfo.setContent(content);
            paymentInfo.setAmount(orderInfo.getTotalAmount());
            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPaymentStatus("0");

            // 保存支付信息
            paymentInfoMapper.insert(paymentInfo);
        }
        return paymentInfo;
    }

    /**
     * 更新支付状态
     *
     * @param paramMap 支付回调参数Map，包含订单号、交易号等信息
     * @param payType 支付类型
     */
    @Override
    public void updatePaymentStatus(Map<String, String> paramMap, Integer payType) {
        // 查询支付信息
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, paramMap.get("out_trade_no")));
        // 如果支付状态已经是成功状态，则直接返回
        if ("1".equals(paymentInfo.getPaymentStatus())){
            return;
        }

        // 更新支付信息
        paymentInfo.setPayType(payType);
        paymentInfo.setPaymentStatus("1");
        paymentInfo.setTradeNo(paramMap.get("trade_no"));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSON.toJSONString(paramMap));
        paymentInfoMapper.updateById(paymentInfo);

        // 发送支付成功消息到消息队列
        rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY, MqConst.ROUTING_PAYMENT_PAY, paymentInfo.getOrderNo());


    }

}